//
//  JSON+AD.swift
//  ADKit
//
//  Created by Adoma on 2020/10/25.
//

import Foundation
import SwiftyJSON
import SmartCodable

public extension String {
    
    var toJSON: JSON {
        let json = JSON(parseJSON: self)
        if json == .null {
            return JSON(self)
        }
        return json
    }
    
    var toData: Data? { data(using: .utf8) }

}

public extension Data {
    
    var toString: String? {
        String(data: self, encoding: .utf8)
    }
}

public extension JSON {
    
    var toString: String? {
        rawString([.jsonSerialization: JSONSerialization.WritingOptions.fragmentsAllowed])
    }
}

public extension SmartEncodable {
    
    var toJSON: JSON? {
        guard let dictionary = toDictionary() else { return nil }
        return JSON(dictionary)
    }
}

public extension SmartDecodable {
    
    static func deserialize(json: JSON) -> Self? {
        switch json.type {
        case .string:
            return deserialize(from: json.string)
        default:
            do {
                let data = try json.rawData()
                return deserialize(from: data)
            } catch {
                return nil
            }
        }
    }
}

public extension Int {
    
    var toString: String { String(self) }
}

public extension String {
    
    var toInt: Int? { Int(self) }
    
    var toIntValue: Int { toInt ?? 0 }
    
    var toFloat: Float? { Float(self) }
    
    var toFloatValue: Float { toFloat ?? 0 }

    var toHex: Int? { Int(self, radix: 16) }
    
    var toHexValue: Int { toHex ?? 0 }
}

public extension Float {
    
    var toString: String { String(self) }

    var toInt: Int { Int(self) }

}

public extension Double {
    
    var toString: String { String(self) }

    var toInt: Int { Int(self) }
   
}


